﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Criterion;

namespace OpenFuse.Cache.Repositories
{
    public class AssetRepository
    {
        public void Save(Asset a)
        {
			if(a.AssetId == Guid.Empty)
				throw new Exception("Null asset id");
			
            using (ISession session = LocalCache.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.SaveOrUpdate(a);
                transaction.Commit();
            }
        }

        public Asset GetByAssetId(Guid assetId)
        {
            using (ISession session = LocalCache.OpenSession())
            {
				Asset a = session.CreateCriteria(typeof(Asset))
					.Add(Restrictions.Eq("AssetId", assetId))
                    .UniqueResult<Asset>();

                return a;
            }
        }
        public Asset GetByNodeId(Guid nodeId)
        {
            using (ISession session = LocalCache.OpenSession())
            {
				Asset a = session.CreateCriteria(typeof(Asset))
					.Add(Restrictions.Eq("NodeId", nodeId))
                    .UniqueResult<Asset>();

                return a;
            }
        }

        public int CountByNodeId(Guid nodeId)
        {
            using (ISession session = LocalCache.OpenSession())
            {
                int cnt = session.CreateCriteria(typeof(Asset))
                    .Add(Restrictions.Eq("NodeId", nodeId))
					.SetProjection(Projections.RowCount())
                    .UniqueResult<int>();
                return cnt;
            }
        }

		public void DeleteAll()
		{
            using (ISession session = LocalCache.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete("from Asset a");
                    transaction.Commit();
				}
            }
		}
	}
}
